using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using PS.WebParts.Rollup.Query;

namespace PS.WebParts.Rollup
{

    public class SqlRollupDataView : ARollupDataSourceView
    {
        public SqlRollupDataView(HttpContext context, IDataSource owner, string viewName)
            : base(context, owner, viewName)
        {
            base.DatesInISO8601 = true;
        }

        override public DataTable RollUpData(SPWeb web)
        {
            IRollupStrategy strategy = new SqlRollupStrategy(this, ContentType);
            return strategy.GetData(web);
        }

        public string ContentType { get; set; }

        public IncludeMetaDataOptions IncludeMetadata { get; set; }



        protected override bool HasRootWebAccess(SPWeb web)
        {
            return true;
        }
    }

    public class CrossSiteDataView : ARollupDataSourceView
    {
        string contentType;
        
        private bool? forceCrossSite;

        public bool? ForceCrossSite
        {
            get { return forceCrossSite; }
            set { forceCrossSite = value; }
        }

        public CrossSiteDataView(HttpContext context, IDataSource owner, string viewName)
            : base(context, owner, viewName)
        {
            base.DatesInISO8601 = true;
        }

        private bool UseSql()
        {
            string useSQLProp = ConfigurationManager.AppSettings["PS.WebParts.Rollup.CrossSiteUseSQL"];
            bool b;
            if (forceCrossSite.HasValue && forceCrossSite.Value ||
                (!string.IsNullOrEmpty(useSQLProp) && bool.TryParse(useSQLProp, out b) && b))
            {
                return true;
            }

            return false;
        }

        /* wrong place?? removed by Eugene
        protected override bool HasRootWebAccess(SPWeb web)
        {
            return UseSql();
        }
         */
        
        override public DataTable RollUpData(SPWeb web)
        {
            IRollupStrategy strategy;

            if (UseSql())
            {
                strategy = new SqlRollupStrategy(this, contentType);
            }
            else
                strategy = new CrossSiteRollupStrategy(this, contentType);

            return strategy.GetData(web);
        }

        public string ContentType
        {
            get { return contentType; }
            set { contentType = value; }
        }
    }
}
